﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FastJSON;
using FineAdmin.Common;
using FineAdmin.IService;
using FineAdmin.Model;
using FineAdmin.Web.Controllers;

namespace FineAdmin.Web.Areas.Posts.Controllers
{
    public class PostSetController : BaseController
    {
        // GET: Posts/PostSet
        public IPostsService PostsService { get; set; }

        public IItemsDetailService ItemsDetailService { get; set; }

        public SelectList BusinessList { get { return new SelectList(ItemsDetailService.GetAll("Id,ItemName,ItemId,ItemCode", "ORDER BY SortCode ASC").Where(x => x.ItemId == 13), "ItemCode", "ItemName"); } }


        public override ActionResult Index(int? id)
        {
            base.Index(id);
            return View();
        }

        [HttpGet]
        public JsonResult List(PostsModel model, PageInfo pageInfo)
        {
            pageInfo.field = "Id";
            pageInfo.order = "asc";
            var result = PostsService.GetListByFilter(model, pageInfo);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Add()
        {
            ViewBag.BusinessList = BusinessList;
            ViewBag.RandomClicks = new Random().Next(100, 200);
            ViewBag.RandomLikes= new Random().Next(10, 50);
            ViewBag.RandomTrample = new Random().Next(0, 5);
            ViewBag.Author = Operator.RealName;
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(PostsModel model)
        {
            model.Likes = 0;
            model.Clicks = 0;
            model.Trample = 0;
            model.CreateTime = DateTime.Now;
            model.CreateUserId = Operator.UserId;
            model.UpdateTime = DateTime.Now;
            model.UpdateUserId = Operator.UserId;
            var result = PostsService.Insert(model) ? SuccessTip("添加成功") : ErrorTip("添加失败");
            return Json(result);
        }

        public ActionResult Edit(int id)
        {
            ViewBag.BusinessList = BusinessList;
            var model = PostsService.GetById(id);
            if (string.IsNullOrWhiteSpace(model.Label)) {
                model.Label = string.Empty;
            }
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(PostsModel model)
        {
            model.UpdateTime = DateTime.Now;
            model.UpdateUserId = Operator.UserId;
            var result = PostsService.UpdateById(model) ? SuccessTip("修改成功") : ErrorTip("修改失败");
            return Json(result);
        }

        [HttpGet]
        public JsonResult Delete(int id)
        {
            var result = PostsService.DeleteById(id) ? SuccessTip("删除成功") : ErrorTip("删除失败");
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult BatchDel(string idsStr)
        {
            var idsArray = idsStr.Substring(0, idsStr.Length - 1).Split(',');
            var result = PostsService.DeleteByIds(idsArray) ? SuccessTip("批量删除成功") : ErrorTip("批量删除失败");
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public IUpFileService UpFileService { get; set; }

        
        public ActionResult ExportFile(string type = "layui")
        {
            UploadFile uploadFile = new UploadFile();
            try
            {
                
                var file = Request.Files[0];    //获取选中文件
                var filecombin = file.FileName.Split('.');
                if (file == null || string.IsNullOrEmpty(file.FileName) || file.ContentLength == 0 || filecombin.Length < 2)
                {
                    uploadFile.code = -1;
                    uploadFile.src = "";
                    uploadFile.msg = "上传出错!请检查文件名或文件内容";
                    return Json(uploadFile, JsonRequestBehavior.AllowGet);
                }
                //定义本地路径位置
                string localPath = Server.MapPath("~/UpFile");
                string filePathName = string.Empty; //最终文件名
                filePathName = Common.Common.CreateNo() + "." + filecombin[1];
                //Upload不存在则创建文件夹
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }
                file.SaveAs(Path.Combine(localPath, filePathName));  //保存图片
                uploadFile.code = 0;
                uploadFile.src = Path.Combine("/UpFile/", filePathName);
                uploadFile.msg = "上传成功";

                //写入数据库
                UpFileService.Insert(new UpFileModel()
                {
                    CreateTime = DateTime.Now,
                    CreateUserId = Operator.UserId,
                    UpdateTime = DateTime.Now,
                    UpdateUserId = Operator.UserId,
                    FileName = file.FileName,
                    FileNewName = filePathName,
                    FilePath = uploadFile.src,
                    FileSize = file.ContentLength.ToString(),
                    FileType = file.ContentType
                });
                //return Json(uploadFile, JsonRequestBehavior.AllowGet);
                if (type == "umeditor")
                {
                    Hashtable infoList = new Hashtable();

                    infoList.Add("state", "SUCCESS");
                    infoList.Add("url", uploadFile.src);
                    infoList.Add("originalName", file.FileName);
                    infoList.Add("name", filePathName);
                    infoList.Add("size", file.ContentLength.ToString());
                    infoList.Add("type", Path.GetExtension(uploadFile.src));

                    return Content(BuildJson(infoList)); 
                    //Response.ContentType = "text/html";
                    //var json = JSON.ToJSON(new { state = "SUCCESS", originalName = uploadFile.src, name = filePathName, size = file.ContentLength, type = file.ContentType });
                    //Response.Write(json);
                    //return Content(json);
                    // return Json(new { state = "SUCCESS", originalName = file.FileName, name = filePathName , size= file.ContentLength, type = Path.GetExtension(uploadFile.src),url= uploadFile.src }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { code = uploadFile.code, msg = uploadFile.msg, data = new { src = uploadFile.src, title = filePathName } }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                uploadFile.code = -1;
                uploadFile.src = "";
                uploadFile.msg = "上传出错!程序异常";
                return Json(new { code = uploadFile.code, msg = uploadFile.msg, data = new { src = uploadFile.src, title = "" } }, JsonRequestBehavior.AllowGet);
            }
        }

        private string BuildJson(Hashtable info)
        {
            List<string> fields = new List<string>();
            string[] keys = new string[] { "originalName", "name", "url", "size", "state", "type" };
            for (int i = 0; i < keys.Length; i++)
            {
                fields.Add(String.Format("\"{0}\": \"{1}\"", keys[i], info[keys[i]]));
            }
            return "{" + String.Join(",", fields) + "}";
        }

    }
}